const cssArray = ['https://cache.amap.com/lbs/static/main1119.css']
const jsArray = [`//webapi.amap.com/maps?v=1.4.15&key=${manateeaiPocConfig.amapKey}`, `//webapi.amap.com/loca?v=1.3.2&key=${manateeaiPocConfig.amapKey}`, '//a.amap.com/Loca/static/dist/jquery.min.js']
const loadJs = (src: string, dom = document.body) =>
  new Promise<void>((resolve) => {
    const script = document.createElement('script')
    script.src = src
    script.type = 'text/javascript'
    script.onload = () => {
      resolve()
    }
    script.onerror = () => {
      resolve()
    }
    dom.append(script)
  })

const loadCss = (href, dom = document.body) =>
  new Promise((resolve) => {
    const link = document.createElement('link')
    link.href = href
    link.rel = 'stylesheet'
    link.onload = () => {
      resolve(link)
    }
    link.onerror = () => {
      resolve(link)
    }
    dom.append(link)
  })

const readyProcess = async () => {
  for (const css of cssArray) {
    await loadCss(css)
  }
  for (const js of jsArray) {
    await loadJs(js)
  }
}

let amapReadyPromise: Promise<void> | null = null
export const amapReady = () => (amapReadyPromise ??= readyProcess())
